<template>
  <div>
    <Header :title="'返回'" :subTitle="'预分计划'" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="款号">
                <a-input v-model="queryParam.productCode" placeholder="请输入" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="品牌">
                <a-select v-model="queryParam.arcBrand" placeholder="请选择" default-value="all" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option v-for="(item, index) in arcBrandsList" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- <a-col :md="8" :sm="24">
              <a-form-item label="品牌">
                <a-select v-model="queryParam.brand" placeholder="请选择" default-value="all" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="all">全部</a-select-option>
                  <a-select-option v-for="(item, index) in brandList" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col> -->
            <a-col :md="8" :sm="24">
              <a-form-item label="波段">
                <a-select v-model="queryParam.bandId" placeholder="请选择" default-value="all" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option v-for="(item, index) in bandsList" :key="index" :value="item.id">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="配货状态">
                <a-select v-model="queryParam.allotstatus" placeholder="请选择" default-value="all" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option :value="0">未入库</a-select-option>
                  <a-select-option :value="1">部分入库</a-select-option>
                  <a-select-option :value="2">全部入库</a-select-option>
                  <a-select-option :value="3">配货中</a-select-option>
                  <a-select-option :value="4">配货完成</a-select-option>
                  <a-select-option :value="5">发货完成</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="预计分配时间">
                <a-range-picker style="width:100%;" showToday valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" v-model="queryParam.preAssignedDate" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="发货时间">
                <a-range-picker style="width:100%;" showToday valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" v-model="queryParam.deliverTime" />
              </a-form-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'left', overflow: 'hidden' }">
                <a-button type="primary" @click="batch = true" v-if="!batch">批量修改</a-button>
                <a-button @click="batchEdit" v-else>完成</a-button>
              </span>
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-popconfirm title="确定导出当前条件下的商品?" ok-text="Yes" cancel-text="No" @confirm="exportConfirm" @cancel="exportCancel">
                  <a-button>导出</a-button>
                </a-popconfirm>
                <a-button icon="plus" style="margin-left: 8px" @click="handleImportXls">导入明细</a-button>
                <a-button style="margin-left: 8px" @click="templateUrl()">下载模版</a-button>
                <a-button style="margin-left: 8px" type="primary" @click="search">查询</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" style="margin-top:32px;">
      <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 2000 }">
        <span slot="adjustQty" slot-scope="text, record">
          <span v-if="!batch">{{ text }}</span>
          <a-input-number v-model="record.adjustQty" v-else />
        </span>
        <span slot="arcBrand" slot-scope="text">
          {{ arcBrandText(text, arcBrandsList) }}
        </span>
        <!-- <span slot="brand" slot-scope="text">
          {{ brandText(text, brandList) }}
        </span> -->
        <span slot="band" slot-scope="text">
          {{ bandText(text, bandsList) }}
        </span>
        <span slot="allotstatus" slot-scope="text">
          {{ text | allotstatus }}
        </span>
        <span slot="remark" slot-scope="text">
          <a-popover :overlayStyle="{ width: '205px', height: 'auto' }">
            <template slot="content">
              <p>{{ text }}</p>
            </template>
            <span class="remark">{{ text }}</span>
          </a-popover>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除该条明细？" @confirm="handleDelete(record)">
            <a href="#">删除</a>
          </a-popconfirm>
        </span>
      </s-table>
    </a-card>
    <DetailEdit ref="detail" @updateTable="updateTable" :brandList="brandList" :bandsList="bandsList" :arcBrandsList="arcBrandsList"></DetailEdit>
    <j-import-modal ref="importModal" :uploadParams="getUploadParams()" @ok="importOk" :serviceId="3" :outId="planId"></j-import-modal>
    <ExportWaitingModal :showExportModal="showExportModal" :exportUploading="exportUploading" :exportFile="exportFile"></ExportWaitingModal>
  </div>
</template>
<script>
import { STable } from '@/views/box/components'
import Header from '@/views/box/components/layouts/Header'
import DetailEdit from './components/detailEdit'
import { queryUploadSuccess } from '@/assets/js/common'
import globalData from '@/assets/js/common'
import JImportModal from '@/components/qiniuUpload/JImportModal'
import { queryAssignedDetailList, batchUpdateAssignedDetail, delAssignedDetailById, delProductPreAssignedDetail, queryPreBand } from '@/api/goods/preAssigned'
import { fetchExportFileId, queryExportSuccess } from '@/assets/js/common'
import { queryDim } from '@/api/goods'
import ExportWaitingModal from '../modules/exportWaitingModal'

const columns = [
  { title: '款号', dataIndex: 'productCode', align: 'center', width: 130, fixed: 'left' },
  { title: '色号', dataIndex: 'productColor', align: 'center', width: 80, fixed: 'left' },
  {
    title: '颜色',
    dataIndex: 'productColorName',
    align: 'center',
    width: 130,
    fixed: 'left'
    // customRender: (text, record) => record.productColor + '/' + text
  },
  { title: '品牌', dataIndex: 'arcBrand', align: 'center', width: 130, fixed: 'left', scopedSlots: { customRender: 'arcBrand' } },
  // { title: '品牌', dataIndex: 'brand', align: 'center', width: 130, fixed: 'left', scopedSlots: { customRender: 'brand' } },
  { title: '波段', dataIndex: 'bandId', align: 'center', width: 130, fixed: 'left', scopedSlots: { customRender: 'band' } },
  { title: '预计入库时间', dataIndex: 'preEntryTime', align: 'center', width: 150 },
  { title: '预计预分开始时间', dataIndex: 'preAssignedBeginTime', align: 'center', width: 150 },
  { title: '预分结束时间', dataIndex: 'preAssignedEndTime', align: 'center', width: 150 },
  { title: '预计生产量', dataIndex: 'preQty', align: 'center', width: 150 },
  { title: '生产调节', dataIndex: 'adjustQty', align: 'center', width: 150, scopedSlots: { customRender: 'adjustQty' } },
  { title: '实际生产量', dataIndex: 'qty', align: 'center', width: 150 },
  { title: '预配仓库存数量', dataIndex: 'ypsl', align: 'center', width: 150 },
  { title: '新品仓库存数量', dataIndex: 'xpsl', align: 'center', width: 150 },
  { title: '已配数量', dataIndex: 'allotsl', align: 'center', width: 150 },
  { title: '配货状态', dataIndex: 'allotstatus', align: 'center', width: 130, scopedSlots: { customRender: 'allotstatus' } },
  { title: '发货时间', dataIndex: 'deliverTime', align: 'center', width: 130 },
  { title: '发货数量', dataIndex: 'sendNum', align: 'center', width: 130 },
  { title: '入库数量', dataIndex: 'inQty', align: 'center', width: 130 },
  { title: '发货波段', dataIndex: 'sendBand', align: 'center', width: 130 },
  { title: '备注', dataIndex: 'remark', align: 'center', width: 130, scopedSlots: { customRender: 'remark' } },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  components: { STable, DetailEdit, JImportModal, Header, ExportWaitingModal },
  data() {
    this.columns = columns
    return {
      planId: '',
      productCode: '',
      batch: false,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      loadData: parameter => this.fetchData(parameter),
      currentList: [],
      queryParam: {
        arcBrand: '',
        // brand: '',
        bandId: '',
        productCode: '',
        allotstatus: ''
      },
      brandList: [],
      bandsList: [],
      arcBrandsList: [],
      showExportModal: false,
      exportUploading: true,
      exportFile: '',
      timer: null
    }
  },
  filters: {
    allotstatus(key) {
      switch (key) {
        case 0:
          return '未入库'
        case 1:
          return '部分入库'
        case 2:
          return '全部入库'
        case 3:
          return '配货中'
        case 4:
          return '配货完成'
        case 5:
          return '发货完成'
      }
    }
  },
  computed: {
    arcBrandText(text, list) {
      return (text, list) => {
        let res = list.filter(e => e.id == text)
        if (res.length > 0) {
          return res[0].attribname
        } else {
          return text
        }
      }
    },
    brandText(text, list) {
      return (text, list) => {
        let res = list.filter(e => e.id == text)
        if (res.length > 0) {
          return res[0].attribname
        } else {
          return text
        }
      }
    },
    bandText(text, list) {
      return (text, list) => {
        let res = list.filter(e => e.id == text)
        if (res.length > 0) {
          return res[0].attribname
        } else {
          return text
        }
      }
    }
  },
  created() {
    this.planId = this.$route.params.id
    this.getSelectList()
    this.getBandList()
  },
  deactivated() {
    // console.log('销毁一下')
    this.$destroy()
  },
  beforeDestroy() {
    // 页面销毁后同时清除定时器，避免占用内存
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    headerBack() {
      this.$router.back()
    },
    fetchData(parameter) {
      let formValue = {}
      Object.keys(this.queryParam).forEach(e => {
        if (e == 'productCode' && this.queryParam.productCode) {
          formValue.productCode = this.queryParam.productCode.trim()
        } else if (e == 'preAssignedDate') {
          formValue.preAssignedBeginDate = this.queryParam[e][0]
          formValue.preAssignedEndDate = this.queryParam[e][1]
        } else if (e == 'deliverTime') {
          formValue.deliverBeginTime = this.queryParam[e][0]
          formValue.deliverEndTime = this.queryParam[e][1]
        } else if (this.queryParam[e] !== '') {
          formValue[e] = this.queryParam[e]
        }
      })
      console.log(formValue)
      let params = {
        page: parameter,
        requestData: {
          productPreAssignedId: this.planId,
          ...formValue
        }
      }
      /* if (this.queryParam.productCode) {
        params.requestData.productCode = this.queryParam.productCode.trim()
      }
      if (this.queryParam.arcBrand != 'all') {
        params.requestData.arcBrand = this.queryParam.arcBrand
      }
      if (this.queryParam.bandId != 'all') {
        params.requestData.bandId = this.queryParam.bandId
      } */
      return queryAssignedDetailList(params).then(res => {
        if (res.code == 0) {
          this.currentList = res.data
          return res
        } else {
          this.$message.warning(res.msg)
          const data = {
            page: {
              pageNo: 0
            },
            data: []
          }
          return data
        }
      })
    },
    search() {
      this.$refs.table.refresh(true)
    },
    reset() {
      this.queryParam = {
        arcBrand: '',
        // brand: '',
        bandId: '',
        productCode: '',
        allotstatus: ''
      }
      this.$refs.table.refresh(true)
    },
    handleEdit(record) {
      if (this.batch) {
        this.$message.warning('请先完成批量编辑！')
      } else {
        this.$refs.detail.show(record)
      }
    },
    confirm(record) {
      let params = {
        requestData: {
          assignedDetailId: record.id
        }
      }
      delAssignedDetailById(params).then(res => {
        if (res.code == 0) {
          this.$message.success('删除成功！')
          this.updateTable()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    batchEdit() {
      console.log(this.currentList)
      let list = this.currentList.map(e => {
        return {
          adJustQty: e.adjustQty,
          id: e.id,
          preQty: e.preQty
        }
      })
      console.log(list)
      let params = {
        requestData: list
      }
      batchUpdateAssignedDetail(params).then(res => {
        if (res.code == 0) {
          this.$message.success('批量修改成功！')
          this.updateTable()
          this.batch = false
        } else {
          this.$message.warning(res.msg)
          this.batch = false
        }
      })
    },
    // 导入
    handleImportXls() {
      this.$refs.importModal.show()
    },
    // 处理上传业务的后台地址
    getImportUrl() {
      return ''
    },
    getUploadParams() {
      // console.log({...globalData.uploadParams})
      return { ...globalData.uploadParams }
    },
    // 上传成功后的方法
    importOk(result) {
      let that = this
      queryUploadSuccess(this.timer, result, 60000, function(x) {
        console.log(x)
        if (x == 'done' || x == 'warning') {
          that.$refs.importModal.close()
          that.$refs.table.refresh(true)
        }
      })
    },
    templateUrl() {
      window.location.href = 'https://img.bzhz.jnbygroup.com/o_1fl64cesh1l7717e1l5d1qhk34dc1.xlsx'
    },
    updateTable() {
      this.$refs.table.refresh()
    },
    // 筛选条件
    getSelectList() {
      return queryDim().then(res => {
        if (res.code === 0) {
          // this.bandsList = res.data.bands
          this.brandList = res.data.brands
          this.arcBrandsList = res.data.arcBrands
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    getBandList() {
      queryPreBand().then(res => {
        if (res.code == 0) {
          this.bandsList = res.data
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 导出
    async exportConfirm(e) {
      console.log(e)
      let formValue = {}
      Object.keys(this.queryParam).forEach(e => {
        if (e == 'productCode' && this.queryParam.productCode) {
          formValue.productCode = this.queryParam.productCode.trim()
        } else if (e == 'preAssignedDate') {
          formValue.preAssignedBeginDate = this.queryParam[e][0]
          formValue.preAssignedEndDate = this.queryParam[e][1]
        } else if (e == 'deliverTime') {
          formValue.deliverBeginTime = this.queryParam[e][0]
          formValue.deliverEndTime = this.queryParam[e][1]
        } else if (this.queryParam[e] !== '') {
          formValue[e] = this.queryParam[e]
        }
      })
      console.log(formValue)
      let params = {
        productPreAssignedId: this.planId,
        ...formValue
      }
      let result = await fetchExportFileId(params, 4)
      if (result) {
        this.exportUploading = true
        this.showExportModal = true
        let that = this
        queryExportSuccess(this.timer, result, 180000, function(x, url) {
          console.log(x, url)
          if (url && x == 'done') {
            that.exportUploading = false
            that.exportFile = url
          } else {
            console.log('解析失败')
            that.showExportModal = false
            // that.$message.warning('解析失败')
          }
        })
      }
    },
    exportCancel(e) {
      console.log(e)
      // this.$message.error('Click on No');
    },
    // 删除
    handleDelete(record) {
      let params = {
        requestData: {
          assignedDetailId: record.id
        }
      }
      delProductPreAssignedDetail(params).then(res => {
        if (res.code == 0) {
          this.$message.success('删除成功！')
          this.$refs.table.refresh()
        } else {
          this.$message.warning(res.msg)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.remark {
  display: inline-block;
  vertical-align: top;
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

